package com.qny.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qny.ai.common.ApiResponse;
import com.qny.ai.dto.role.RoleCreateRequest;
import com.qny.ai.dto.role.RoleUpdateRequest;
import com.qny.ai.entity.AppRole;
import com.qny.ai.entity.RoleRating;
import com.qny.ai.service.RoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/roles")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    @PostMapping
    public ApiResponse<Long> create(HttpServletRequest request, @Valid @RequestBody RoleCreateRequest createRequest) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("创建角色请求 - 用户ID: {}, 角色名称: {}", userId, createRequest.getName());
        if (userId == null) {
            log.warn("用户未登录，无法创建角色");
            return ApiResponse.fail(401, "用户未登录");
        }
        Long id = roleService.createRole(userId, createRequest);
        log.info("角色创建成功 - 角色ID: {}", id);
        return ApiResponse.ok(id);
    }

    @PostMapping("/update")
    public ApiResponse<Boolean> update(@Valid @RequestBody RoleUpdateRequest request) {
        return ApiResponse.ok(roleService.updateRole(request));
    }

    @GetMapping("/my")
    public ApiResponse<Page<AppRole>> getMyRoles(HttpServletRequest request,
                                                 @RequestParam(defaultValue = "1") int pageNo,
                                                 @RequestParam(defaultValue = "10") int pageSize) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取我的角色请求 - 用户ID: {}, 页码: {}, 页大小: {}", userId, pageNo, pageSize);
        if (userId == null) {
            log.warn("用户未登录，无法获取角色列表");
            return ApiResponse.fail(401, "用户未登录");
        }
        Page<AppRole> result = roleService.getMyRoles(userId, pageNo, pageSize);
        log.info("返回角色列表 - 总数: {}, 当前页记录数: {}", result.getTotal(), result.getRecords().size());
        return ApiResponse.ok(result);
    }

    @GetMapping("/favorites")
    public ApiResponse<Page<AppRole>> getFavoriteRoles(HttpServletRequest request,
                                                       @RequestParam(defaultValue = "1") int pageNo,
                                                       @RequestParam(defaultValue = "10") int pageSize) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("获取收藏角色请求 - 用户ID: {}, 页码: {}, 页大小: {}", userId, pageNo, pageSize);
        if (userId == null) {
            log.warn("用户未登录，无法获取收藏角色列表");
            return ApiResponse.fail(401, "用户未登录");
        }
        Page<AppRole> result = roleService.getFavoriteRoles(userId, pageNo, pageSize);
        log.info("返回收藏角色列表 - 总数: {}, 当前页记录数: {}", result.getTotal(), result.getRecords().size());
        return ApiResponse.ok(result);
    }

    @GetMapping("/{id}")
    public ApiResponse<AppRole> detail(@PathVariable("id") Long id) {
        return ApiResponse.ok(roleService.getById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> delete(@PathVariable("id") Long id) {
        return ApiResponse.ok(roleService.deleteById(id));
    }

    @GetMapping
    public ApiResponse<Page<AppRole>> list(@RequestParam(defaultValue = "1") int pageNo,
                                           @RequestParam(defaultValue = "10") int pageSize,
                                           @RequestParam(required = false) String keyword) {
        return ApiResponse.ok(roleService.pageList(pageNo, pageSize, keyword));
    }

//    @GetMapping("/search")
//    public ApiResponse<Page<AppRole>> search(@RequestParam(required = false) String keyword,
//                                             @RequestParam(required = false) String status,
//                                             @RequestParam(required = false) String privacy,
//                                             @RequestParam(required = false, defaultValue = "createdAt") String sortBy,
//                                             @RequestParam(required = false, defaultValue = "false") boolean asc,
//                                             @RequestParam(defaultValue = "1") int pageNo,
//                                             @RequestParam(defaultValue = "10") int pageSize) {
//        return ApiResponse.ok(roleService.search(keyword, status, privacy, sortBy, asc, pageNo, pageSize));
//    }
    
    @PostMapping("/{id}/use")
    public ApiResponse<Boolean> incrementUsage(@PathVariable("id") Long roleId) {
        return ApiResponse.ok(roleService.incrementUsage(roleId));
    }

    @PostMapping("/{id}/publish")
    public ApiResponse<Boolean> publishRole(@PathVariable("id") Long roleId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("发布角色请求 - 用户ID: {}, 角色ID: {}", userId, roleId);
        if (userId == null) {
            log.warn("用户未登录，无法发布角色");
            return ApiResponse.fail(401, "用户未登录");
        }
        boolean success = roleService.publishRole(roleId, userId);
        log.info("角色发布结果 - 角色ID: {}, 成功: {}", roleId, success);
        return ApiResponse.ok(success);
    }

    @PostMapping("/{id}/unpublish")
    public ApiResponse<Boolean> unpublishRole(@PathVariable("id") Long roleId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("停止发布角色请求 - 用户ID: {}, 角色ID: {}", userId, roleId);
        if (userId == null) {
            log.warn("用户未登录，无法停止发布角色");
            return ApiResponse.fail(401, "用户未登录");
        }
        boolean success = roleService.unpublishRole(roleId, userId);
        log.info("角色停止发布结果 - 角色ID: {}, 成功: {}", roleId, success);
        return ApiResponse.ok(success);
    }

    @GetMapping("/hot")
    public ApiResponse<List<AppRole>> getHotRoles() {
        log.info("获取热门角色请求");
        List<AppRole> hotRoles = roleService.getHotRoles();
        log.info("获取热门角色结果 - 数量: {}", hotRoles.size());
        return ApiResponse.ok(hotRoles);
    }

    @GetMapping("/search")
    public ApiResponse<Page<AppRole>> searchRoles(@RequestParam(required = false) String keyword,
                                                   @RequestParam(required = false) String status,
                                                   @RequestParam(required = false) String privacy,
                                                   @RequestParam(required = false) String category,
                                                   @RequestParam(required = false) String sortBy,
                                                   @RequestParam(required = false) Boolean asc,
                                                   @RequestParam(defaultValue = "1") int pageNo,
                                                   @RequestParam(defaultValue = "20") int pageSize) {
        log.info("搜索角色请求 - 关键词: {}, 状态: {}, 隐私: {}, 分类: {}, 排序: {}, 页码: {}, 页大小: {}", 
                keyword, status, privacy, category, sortBy, pageNo, pageSize);
        Page<AppRole> result = roleService.searchRoles(keyword, status, privacy, category, sortBy, asc, pageNo, pageSize);
        log.info("搜索角色结果 - 总数: {}, 当前页记录数: {}", result.getTotal(), result.getRecords().size());
        return ApiResponse.ok(result);
    }

    @GetMapping("/public/{id}")
    public ApiResponse<AppRole> getPublicRole(@PathVariable("id") Long roleId) {
        log.info("获取公共角色详情 - 角色ID: {}", roleId);
        AppRole role = roleService.getPublicRole(roleId);
        if (role == null) {
            log.warn("公共角色不存在 - 角色ID: {}", roleId);
            return ApiResponse.fail(404, "角色不存在");
        }
        log.info("获取公共角色详情成功 - 角色ID: {}, 角色名称: {}", roleId, role.getName());
        return ApiResponse.ok(role);
    }

    @PostMapping("/{id}/favorite")
    public ApiResponse<Boolean> toggleFavorite(@PathVariable("id") Long roleId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        log.info("收藏角色请求 - 用户ID: {}, 角色ID: {}", userId, roleId);
        if (userId == null) {
            log.warn("用户未登录，无法收藏角色");
            return ApiResponse.fail(401, "用户未登录");
        }
        boolean success = roleService.toggleFavorite(roleId, userId);
        log.info("角色收藏结果 - 角色ID: {}, 用户ID: {}, 成功: {}", roleId, userId, success);
        return ApiResponse.ok(success);
    }

    @GetMapping("/{id}/reviews")
    public ApiResponse<List<RoleRating>> getRoleReviews(@PathVariable("id") Long roleId,
                                                        @RequestParam(defaultValue = "1") int pageNo,
                                                        @RequestParam(defaultValue = "10") int pageSize) {
        log.info("获取角色评价 - 角色ID: {}, 页码: {}, 页大小: {}", roleId, pageNo, pageSize);
        List<RoleRating> reviews = roleService.getRoleReviews(roleId, pageNo, pageSize);
        log.info("获取角色评价结果 - 角色ID: {}, 评价数量: {}", roleId, reviews.size());
        return ApiResponse.ok(reviews);
    }

    @PostMapping("/{id}/rating")
    public ApiResponse<Boolean> addRoleRating(@PathVariable("id") Long roleId,
                                              @RequestBody Map<String, Object> request,
                                              HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        log.info("添加角色评价请求 - 用户ID: {}, 角色ID: {}", userId, roleId);
        if (userId == null) {
            log.warn("用户未登录，无法添加评价");
            return ApiResponse.fail(401, "用户未登录");
        }
        
        Integer rating = (Integer) request.get("rating");
        String comment = (String) request.get("comment");
        
        boolean success = roleService.addRoleRating(roleId, userId, rating, comment);
        log.info("添加角色评价结果 - 角色ID: {}, 用户ID: {}, 成功: {}", roleId, userId, success);
        return ApiResponse.ok(success);
    }

    @PutMapping("/rating/{ratingId}")
    public ApiResponse<Boolean> updateRoleRating(@PathVariable("ratingId") Long ratingId,
                                                 @RequestBody Map<String, Object> request,
                                                 HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        log.info("更新角色评价请求 - 用户ID: {}, 评价ID: {}", userId, ratingId);
        if (userId == null) {
            log.warn("用户未登录，无法更新评价");
            return ApiResponse.fail(401, "用户未登录");
        }
        
        Integer rating = (Integer) request.get("rating");
        String comment = (String) request.get("comment");
        
        boolean success = roleService.updateRoleRating(ratingId, userId, rating, comment);
        log.info("更新角色评价结果 - 评价ID: {}, 用户ID: {}, 成功: {}", ratingId, userId, success);
        return ApiResponse.ok(success);
    }

    @DeleteMapping("/rating/{ratingId}")
    public ApiResponse<Boolean> deleteRoleRating(@PathVariable("ratingId") Long ratingId,
                                                 HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        log.info("删除角色评价请求 - 用户ID: {}, 评价ID: {}", userId, ratingId);
        if (userId == null) {
            log.warn("用户未登录，无法删除评价");
            return ApiResponse.fail(401, "用户未登录");
        }
        
        boolean success = roleService.deleteRoleRating(ratingId, userId);
        log.info("删除角色评价结果 - 评价ID: {}, 用户ID: {}, 成功: {}", ratingId, userId, success);
        return ApiResponse.ok(success);
    }
}


